/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: WirelessClient.cpp,v 1.5 2009-10-26 12:47:02 morsko Exp $
 *
 * \file
 * \brief Implementation for Wireless interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 */

#include "WirelessClient.hpp"
#include "WirelessData.hpp"

//*****************************************************************************
using namespace MaCI::Wireless;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CWirelessClient::CWirelessClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : // CSync(2,1),
    // CThread(1),
  CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_WIRELESS, aInterfaceMinor),
  iWirelessSequence(0),
  iLastWirelessData()
{
  dPrint(4,"CWirelessClient %p constructed", this);
}
//*****************************************************************************

CWirelessClient::~CWirelessClient()
{
  DoClose();
  dPrint(4,"CWirelessClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CWirelessClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      //      CThread::RunThread();
      dPrint(4,"CWirelessClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"WirelessClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CWirelessClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    ///* CThread::CancelThread(); //Removed by script */
    //
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed WirelessClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
    
  } else {
    dPrint(4, "WirelessClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

bool CWirelessClient::WaitWirelessEvent(CWirelessData &aData, 
                                  const unsigned int aTimeout_ms)
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  if (IsActive()) {
    
    // Call the ReceiveMessage wrapper with 2s timeout
    result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
    
    // If result is OK, process the msg.
    if (result == KMaCIOK) {
      bool r;
      gim::binbag::CBinBag bb;
      CWirelessData d;
      
      // Decode BinBag.
      r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
      if (r) {
        // BinBag OK. Decode WirelessData.
        r = d.DecodeFrom(&bb);
        if (r && ( 
                  d.GetNodeSignalArray().size() ||
                  d.GetNodeRangeArray().size() ||
                  d.GetNodePositionArray().size()) ) {
          // WirelessData ok. Copy to caller.
          aData.Copy(d);
          
        } else {
          result = KMaCIInvalidFormat;
          
        }
        
      } else {
        result = KMaCIInvalidFormat;
        
      }
    }
  } else {
    result = KMaCINotActive;

  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CWirelessClient::SendCommand(CWirelessData &aWirelessData)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aWirelessData.GetCommand()) {
      // Foo.
      ++iWirelessSequence;
      
      // Send.
      SendInterfaceMessage(aWirelessData.GetBinBagContainerPtr()->GetBuffer(),
                           aWirelessData.GetBinBagContainerPtr()->GetBufferSize(),
                           iWirelessSequence);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d, seq: %d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             iWirelessSequence-1,
             aWirelessData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CWirelessData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send WirelessData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
/*
int CWirelessClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CWirelessData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Wireless, now handle contents
      Lock();
      if (id.IsWirelessContainer()) {
        iLastWirelessData = id;
        ++iWirelessSequence;
        Notify(KEventNewWireless);
        dPrint(10,"Got WirelessData, Sequence now %u", iWirelessSequence);
      }
      
      // Check whether the element contains
      if (id.IsSourceInfoContainer()) {
        iSourceInfoMap = id.GetSourceInfoMap();
        iSourceInfoMapReceived = true;
        Notify(KEventSourceInfoMap);
      }
      Unlock();

    } else {
      dPrint(4,"WARNING: Received Wireless interface message, but failed to decode as WirelessData!");
      
    }
  }
  
  return result;
}
*/
//*****************************************************************************
/*
  // Thread processing functions are not used here, but are left here
  // as an example.

int CWirelessClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

    } else if (e != KMaCITimeout) {
      // Other error, try to recover by sleeping one second.
      dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping...",
             e);
      ownSleep_ms(1000);
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");

  return result;
}
*/
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
